package com.sdry.web.controller.jyy;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.sdry.model.barCodeOperation.BarCodeOperation;
import com.sdry.model.jyy.Receive;
import com.sdry.model.jyy.ReceiveDetail;
import com.sdry.model.jyy.ReceiveDetailQuality;
import com.sdry.model.jyy.Workload;
import com.sdry.model.lz.BarCodeConversionRecord;
import com.sdry.model.lz.CodeMark;
import com.sdry.model.lz.LzQueryCriteria;
import com.sdry.model.lz.ReceiveMark;
import com.sdry.model.zc.ZcGeneralQueryEntity;
import com.sdry.model.zc.ZcInventoryInfoEntity;
import com.sdry.model.zc.ZcMaterielAndTrayEntity;
import com.sdry.model.zc.ZcTrayAndLocationEntity;
import com.sdry.service.barCodeOperation.BarCodeOperationService;
import com.sdry.service.jyy.ErrorServise;
import com.sdry.service.jyy.ReceiveDetailService;
import com.sdry.service.jyy.ReceiveService;
import com.sdry.service.jyy.UpService;
import com.sdry.service.jyy.unpack.UnpackDetalService;
import com.sdry.service.llm.CancellingStockDetailService;
import com.sdry.service.llm.DevaningWorkService;
import com.sdry.service.llm.InquiryBusinessService;
import com.sdry.service.lz.InventoryService;
import com.sdry.service.lz.MaterielService;
import com.sdry.service.lz.StockOutOrderService;
import com.sdry.service.tdd.UnpackingService;
import com.sdry.service.tdd.emailRecord.EmailRecordService;
import com.sdry.service.zc.ZcBindAndUnbindService;
import com.sdry.service.zc.ZcInventoryManagementService;
import com.sdry.service.zc.ZcSimplificationInService;
import com.sdry.utils.DateUtil;
import com.sdry.utils.ResponseUtil;

/**
 * 收货和入库的app接口
 * @author jyy
 * @2019-05-16 14:15:38
 * LZ修改记录
 * 1、lz2019年11月5日在77行引入log，在2019年11月7日78行引入AFFECT_ROW变量，79引入AFFECT_ROW_STRING变量；
 * 2、110行左右新增warehouse_id字段；351行左右新增warehouse_id字段，
 * 3、拆分submitReceive接口，拆分为imgUpload(190行左右)、insertCustomerCode(225行左右)、insertEmailInfo(260行左右)方法，在submitReceive里调用；
 * 
 * 修改人：连雷明
 * 修改时间：2019-11-08
 * 修改内容：给方法submitReceipt，1730-1732行，加参数，仓库ID
 */
@RequestMapping("/app")
@Controller
public class AppJyController {
	private final static Logger log = LoggerFactory.getLogger(AppJyController.class);
	private final static int AFFECT_ROW = 0;

	@Resource ReceiveService ReceiveService;
	@Resource ReceiveDetailService ReceiveDetailService;
	@Resource InquiryBusinessService inquiryBusinessService;
	@Resource UpService upService;
	@Resource ZcInventoryManagementService zcInventoryManagementService;
	@Resource UnpackingService unpackingService;
	@Resource MaterielService materielService;
	@Resource ZcBindAndUnbindService zcBindAndUnbindService;
	@Resource CancellingStockDetailService cancellingStockDetailService;
	@Resource DevaningWorkService devaningWorkService;
	@Resource ZcSimplificationInService zcSimplificationInService;
	@Resource BarCodeOperationService barCodeOperationService;
	@Resource InventoryService inventoryService;
	@Resource StockOutOrderService stockOutService;
	@Resource UnpackDetalService unpackDetalService;
	@Resource ErrorServise errorServise;
	@Resource EmailRecordService emailRecordService;

	//计数循环次数	
	//int count;
	/**
	 * 查询所有未收货的收货单APP
	 * @param response 
	 */
	@RequestMapping("/selectAllReceive")
	public void selectAllReceive(String warehouse_id, HttpServletResponse response, HttpSession session) {
		//LZ新增仓库id字段
		//Long warehouse_id = (Long) session.getAttribute("warehouse_id");
		Receive param = new Receive();
		//未收货
		param.setState(AFFECT_ROW);
		param.setIsSimple("0");
		//LZ添加warehouse_id
		param.setWarehouse_id(Long.valueOf(warehouse_id));
		List<Receive> list = ReceiveService.queryAllByMution(param);
		JSONObject jsonObject = new JSONObject();
		int count = list.size();
		if (count > AFFECT_ROW) {
			//传递数据到页面
		    jsonObject.put("status", "1");
		    jsonObject.put("message", "");
		    jsonObject.put("data", list);
		}else {
			//传递数据到页面
		    jsonObject.put("status", "0");
		    jsonObject.put("message", "查询数据为空");
		    jsonObject.put("data", list);
		}
		try {
			ResponseUtil.write(response, jsonObject);
		} catch (Exception e) {
			log.info("lz进入给app查询所有未收货的收货单的方法出现异常");
			e.printStackTrace();
		}
	}
	
	/**
	 * 根据收货单号查询收货详情
	 * @param receiveNumber 收货单号
	 * @param response 响应
	 */
	@RequestMapping("/selectReceiveDtailByNumber")
	public void selectReceiveDtailByNumber(String receiveNumber, HttpServletResponse response, HttpSession session) {
		log.info("lz进入根据收货单号查询收货详情的方法:receiveNumber=" + receiveNumber);
		ReceiveDetail param = new ReceiveDetail();
		param.setReceiveNumber(receiveNumber);
		List<ReceiveDetail> list = ReceiveDetailService.queryAllByMution(param);
		JSONObject jsonObject = new JSONObject();
		int count = list.size();
		if (count > AFFECT_ROW) {
			//传递数据到页面
		    jsonObject.put("status", "1");
		    jsonObject.put("message", "");
		    jsonObject.put("data", list);
		}else {
			//传递数据到页面
		    jsonObject.put("status", "0");
		    jsonObject.put("message", "查询数据为空");
		    jsonObject.put("data", list);
		}
		try {
			ResponseUtil.write(response, jsonObject);
		} catch (Exception e) {
			log.info("lz根据收货单号查询收货详情的方法出现异常");
			e.printStackTrace();
		}
	}
	
	/**
	 * APP收货提交的接口，lz2019年11月4日 15:30:19修改
	 * @param Details app扫描的收货单详细
	 * @param person 提交人(操作人)id
	 * @param sure_name 
	 * @param pic_key 图片上传路径
	 * @param response
	 * @param session
	 */
	@RequestMapping("/submitReceive")
	public void submitReceive(String Details, String person, List<MultipartFile> pic_key,
			String sure_name, HttpServletResponse response, HttpSession session, String warehouse_id) {
		//LZ新增仓库id字段
        //Long warehouse_id = (Long) session.getAttribute("warehouse_id");
        //warehouse_id = 14L;
		Integer affect = upService.submitReceive(Details, person, pic_key, sure_name, Long.parseLong(warehouse_id));
		JSONObject jsonObject = new JSONObject();
		if(affect > AFFECT_ROW) {
			//传递数据到页面
		    jsonObject.put("status", "1");
		    jsonObject.put("message", "");
		    jsonObject.put("data", "提交成功");
		} else {
			//传递数据到页面
		    jsonObject.put("status", "0");
		    jsonObject.put("message", "提交失败");
		    jsonObject.put("data", "0");
		}
		try {
			ResponseUtil.write(response, jsonObject);
		} catch (Exception e) {
			log.info("APP的收货提交方法出现异常");
			e.printStackTrace();
		}
	}
	
	/**
	 * 根据物料id查询，存放该物料的仓库、库区、库位信息
	 * @param mid 物料id
	 * @param response 响应
	 * @throws Exception 
	 */
	/*@RequestMapping("/selectWarehouseByMid")
	public void selectWarehouseByMid(String mid, String customer, HttpServletResponse response) throws Exception {
		Up up = new Up();
		//物料id
		if(mid != null && mid != "") {
			up.setMid(Long.valueOf(mid));
		}
		//供应商id
		if(customer != null) {
			up.setCustomerId(Long.valueOf(customer));
		}
		List<LlmWarehouseStock> list = new ArrayList<LlmWarehouseStock>();
		
		if(mid != null && mid != "") {
			list = ReceiveService.selectWarehouseByMid(up);
		}else {
			list = inquiryBusinessService.appGetStock();
		}
		
		JSONObject jsonObject = new JSONObject();
		int count = list.size();
		if (count > 0) {
			//传递数据到页面
		    jsonObject.put("status", "1");
		    jsonObject.put("message", "");
		    jsonObject.put("data", list);
		}else {
			//传递数据到页面
		    jsonObject.put("status", "0");
		    jsonObject.put("message", "查询数据为空");
		    jsonObject.put("data", list);
		}
		ResponseUtil.write(response, jsonObject);
	}*/
	
	
	/**
	 * 质检后的条码绑定
	 * @param json 质检后的条码绑定
	 * @param response
	 * @throws Exception 
	 */
	@RequestMapping("/comeku")
	public void comeku(String json, String person, HttpServletResponse response, String warehouse_id) {
		String addStr = "";
		Long affact = 0L;
		Gson gson = new Gson();
		List<ReceiveDetailQuality> receiveDetailQualityList = gson.fromJson(json, new TypeToken<List<ReceiveDetailQuality>>() {}.getType());
		for (ReceiveDetailQuality receiveDetailQuality : receiveDetailQualityList) {
			for (int j = 0; j < receiveDetailQuality.getReceiveCode().size(); j++) {
				CodeMark exitCodeMark = ReceiveDetailService.queryCodeMarkByCode(receiveDetailQuality.getReceiveCode().get(j));
				if (exitCodeMark != null) {
					//根据精准码修改质检区库存的数量
					/*ReceiveDetailService.updateInventoryInfoQuality(receiveDetailQuality.getMid() + "", 
							receiveDetailQuality.getPici(), (exitCodeMark.getNum() - receiveDetailQuality.getReceiveCode().get(j).getNum()) + "");*/
					CodeMark codeMark = new CodeMark();
					codeMark.setCode(exitCodeMark.getCode());
					codeMark.setNum(receiveDetailQuality.getReceiveCode().get(j).getNum());
					//传入查询到的条码和提交的数量
					affact = ReceiveDetailService.updateCodeMark(codeMark);
				} else {
					CodeMark codeMark = new CodeMark();
					codeMark.setReceive_detail_id(receiveDetailQuality.getId());
					codeMark.setCode(receiveDetailQuality.getReceiveCode().get(j).getCode());
					codeMark.setNum(receiveDetailQuality.getReceiveCode().get(j).getNum());
					codeMark.setIs_ng(receiveDetailQuality.getReceiveCode().get(j).getIs_ng());
					//添加每种物料对应的多个条码
					ReceiveDetailService.addCodeMark(receiveDetailQuality.getReceiveCode().get(j));
					addStr += receiveDetailQuality.getReceiveCode().get(j).getCode() + ",";
				}
				//绑定后修改质检的状态为2
				ReceiveDetailService.updateReceiveDetailQuality2(receiveDetailQuality.getId() + "");
				//拆箱
				//ReceiveDetailService.uncomeku(code);
			}
		}
		//质检后同步质检区
		Date date = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		ZcMaterielAndTrayEntity zcMaterielAndTrayEntity = new ZcMaterielAndTrayEntity();
		zcMaterielAndTrayEntity.setMateriel_code(addStr);
		zcMaterielAndTrayEntity.setBinding_person(Long.parseLong(person));
		zcMaterielAndTrayEntity.setBinding_date(sdf.format(date));
		zcMaterielAndTrayEntity.setTargetRegion("待上架区");
		//zcMaterielAndTrayEntity.setTray_code(tray_code);
		//zcMaterielAndTrayEntity.setLocation_code(location_code);
		int affact2 = zcBindAndUnbindService.bindAndUp2SpecialArea(zcMaterielAndTrayEntity, Long.parseLong(warehouse_id));
		JSONObject jsonObject = new JSONObject();
		if (affact > AFFECT_ROW) {
			//传递数据到页面
			jsonObject.put("status", "1");
			jsonObject.put("message", "");
			jsonObject.put("data", "提交成功");
		} else {
			//传递数据到页面
			jsonObject.put("status", "0");
			jsonObject.put("message", "提交失败");
			jsonObject.put("data", "0");
		}
		
		//----------------------给历史记录表插入数据   start-------------------------------------
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String time = format.format(new Date());
		for (ReceiveDetailQuality receiveDetailQuality : receiveDetailQualityList) {
			for (int j = 0; j < receiveDetailQuality.getReceiveCode().size(); j++) {
				BarCodeOperation bar = new BarCodeOperation();
				bar.setBarCode(receiveDetailQuality.getReceiveCode().get(j).getCode());
				bar.setCodeNum(receiveDetailQuality.getReceiveCode().get(j).getNum());
				bar.setBatch(receiveDetailQuality.getPici());
				bar.setOperator(Long.parseLong(person));
				bar.setOperatingTime(time);
				bar.setMaterielId(receiveDetailQuality.getMid());
				bar.setType("质检");
				//lz新增warehouse_id
				bar.setWarehouse_id(Long.parseLong(warehouse_id));
				if(affact > AFFECT_ROW){
					bar.setResult("成功");
				} else {
					bar.setResult("失败");
				}
				barCodeOperationService.insert(bar);
			}
		}
		//----------------------给历史记录表插入数据   end-------------------------------------
				
		try {
			ResponseUtil.write(response, jsonObject);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 拆箱校验
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("/selectAccurateByCodeApp")
	public void selectAccurateByCodeApp(HttpServletResponse response, String mcode, String warehouse_id) {
		JSONObject jsonObject = new JSONObject();
		String location_code = zcBindAndUnbindService.selectByMaterielCode(mcode + ",", Long.parseLong(warehouse_id));
		if("SY".equals(location_code)){
			jsonObject.put("status", "0");
			jsonObject.put("message", "该条码在损溢区");
			try {
				ResponseUtil.write(response, jsonObject);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}else{
			//根据mcode查询收货单详细
			CodeMark codeMark = ReceiveDetailService.queryReceiveDetailIdByMcode(mcode);
			if (codeMark != null) {
				List<ReceiveDetail> receiveDetailList = ReceiveDetailService.selectAccurateByCodeApp(codeMark.getReceive_detail_id());
				if (receiveDetailList.size() > 0) {
					ZcMaterielAndTrayEntity zcMaterielAndTrayEntity = zcBindAndUnbindService.selectMaterielLocationByCodeDown(mcode, Long.parseLong(warehouse_id));
					if(zcMaterielAndTrayEntity.getMateriel_code() != null && !"".equals(zcMaterielAndTrayEntity.getMateriel_code())){
						receiveDetailList.get(0).getReceiveCode().add(codeMark);
						//传递数据到页面
						jsonObject.put("status", "0");
						jsonObject.put("message", "此物料未下架");
						jsonObject.put("data", receiveDetailList.get(0));
					} else {
						receiveDetailList.get(0).getReceiveCode().add(codeMark);
						//传递数据到页面
						jsonObject.put("status", "1");
						jsonObject.put("message", "此物料已下架");
						jsonObject.put("data", receiveDetailList.get(0));
					}
				} else {
					//传递数据到页面
					jsonObject.put("status", "0");
					jsonObject.put("message", "查询不到此条码");
					jsonObject.put("data", null);
				}
				try {
					ResponseUtil.write(response, jsonObject);
				} catch (Exception e) {
					e.printStackTrace();
				}
			} else {
				/*codemark表中无此条码
				1.先在条码记录表中查询有没有，有，则表示此条码已出库。
				2.没有，就在receivemark表中查询，有，则表示，条码未收货，没有，表示系统无此条码*/
				
				//根据条码在条码记录表中查询此条码的信息
				BarCodeOperation param = new BarCodeOperation();
				param.setBarCode(mcode);
				List<BarCodeOperation> list = barCodeOperationService.queryAllByMution(param);
				
				if(list.size() > 0) {
					param.setWarehouse_id(Long.valueOf(warehouse_id));
					//根据条码和仓库id在操作记录表中查询此条码,存在，条码已出库，不存在，条码在别的仓库
					List<BarCodeOperation> list2 = barCodeOperationService.queryAllByMution(param);
					
					if(list2.size() > 0) {
						//此条码已出库
						//传递数据到页面
						jsonObject.put("status", "0");
						jsonObject.put("message", "条码已出库");
						jsonObject.put("data", null);
					}else {
						//此条码已出库
						//传递数据到页面
						jsonObject.put("status", "0");
						jsonObject.put("message", "该条码不属于本仓库");
						jsonObject.put("data", null);
					}
				}else {
					
					//根据条码，在receivemark表中查询
					ReceiveMark receiveMark = ReceiveDetailService.selectReceiveMarkByCode(mcode);
					
					if(receiveMark != null) {
						//传递数据到页面
						jsonObject.put("status", "0");
						jsonObject.put("message", "条码未收货，收货单号："+receiveMark.getReceiveDetail().getReceiveNumber());
						jsonObject.put("data", null);
					}else {
						//传递数据到页面
						jsonObject.put("status", "0");
						jsonObject.put("message", "系统无此条码");
						jsonObject.put("data", null);
					}
					
				}
				
				try {
					ResponseUtil.write(response, jsonObject);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	}
	/**
	 * 拆箱校验（新）
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("/selectAccurateByCodeApp2")
	public void selectAccurateByCodeApp2(HttpServletResponse response, String mcode, String warehouse_id) {
		JSONObject jsonObject = new JSONObject();
		//根据mcode查询收货单详细
		CodeMark codeMark = ReceiveDetailService.queryReceiveDetailIdByMcode(mcode);
		if (codeMark != null) {
			List<ReceiveDetail> receiveDetailList = ReceiveDetailService.selectAccurateByCodeApp(codeMark.getReceive_detail_id());
			if (receiveDetailList.size() > 0) {
				ZcMaterielAndTrayEntity zcMaterielAndTrayEntity = zcBindAndUnbindService.selectMaterielLocationByCodeDown(mcode, Long.parseLong(warehouse_id));
				if(zcMaterielAndTrayEntity.getMateriel_code() != null && !"".equals(zcMaterielAndTrayEntity.getMateriel_code())){
					receiveDetailList.get(0).getReceiveCode().add(codeMark);
					//传递数据到页面
					jsonObject.put("status", "0");
					jsonObject.put("message", "此物料未下架");
					jsonObject.put("data", receiveDetailList.get(0));
				} else {
					//根据物料id查询最早的批次
					String oldPici = ReceiveDetailService.selectOldPiciByMid(receiveDetailList.get(0).getMid());
					receiveDetailList.get(0).setOldPici(oldPici);
					receiveDetailList.get(0).getReceiveCode().add(codeMark);
					
					//传递数据到页面
					jsonObject.put("status", "1");
					jsonObject.put("message", "此物料已下架");
					jsonObject.put("data", receiveDetailList.get(0));
				}
			} else {
				//传递数据到页面
				jsonObject.put("status", "0");
				jsonObject.put("message", "查询不到此条码");
				jsonObject.put("data", null);
			}
			try {
				ResponseUtil.write(response, jsonObject);
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {
			/*codemark表中无此条码
			1.先在条码记录表中查询有没有，有，则表示此条码已出库。
			2.没有，就在receivemark表中查询，有，则表示，条码未收货，没有，表示系统无此条码*/
			
			//根据条码在条码记录表中查询此条码的信息
			BarCodeOperation param = new BarCodeOperation();
			param.setBarCode(mcode);
			List<BarCodeOperation> list = barCodeOperationService.queryAllByMution(param);
			
			if(list.size() > 0) {
				param.setWarehouse_id(Long.valueOf(warehouse_id));
				//根据条码和仓库id在操作记录表中查询此条码,存在，条码已出库，不存在，条码在别的仓库
				List<BarCodeOperation> list2 = barCodeOperationService.queryAllByMution(param);
				
				if(list2.size() > 0) {
					//此条码已出库
					//传递数据到页面
					jsonObject.put("status", "0");
					jsonObject.put("message", "条码已出库");
					jsonObject.put("data", null);
				}else {
					//此条码已出库
					//传递数据到页面
					jsonObject.put("status", "0");
					jsonObject.put("message", "该条码不属于本仓库");
					jsonObject.put("data", null);
				}
			}else {
				
				//根据条码，在receivemark表中查询
				ReceiveMark receiveMark = ReceiveDetailService.selectReceiveMarkByCode(mcode);
				
				if(receiveMark != null) {
					//传递数据到页面
					jsonObject.put("status", "0");
					jsonObject.put("message", "条码未收货，收货单号："+receiveMark.getReceiveDetail().getReceiveNumber());
					jsonObject.put("data", null);
				}else {
					//传递数据到页面
					jsonObject.put("status", "0");
					jsonObject.put("message", "系统无此条码");
					jsonObject.put("data", null);
				}
				
			}
			
			try {
				ResponseUtil.write(response, jsonObject);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	/**
	 * 根据条码查询状态（紧急收货单）
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("/urgencySelectAccurateByCodeApp")
	public void urgencySelectAccurateByCodeApp(HttpServletResponse response, String mcode, String warehouse_id) {
		JSONObject jsonObject = new JSONObject();
		String location_code = zcBindAndUnbindService.selectByMaterielCode(mcode + ",", Long.parseLong(warehouse_id));
		if("SY".equals(location_code)){
			jsonObject.put("status", "0");
			jsonObject.put("message", "该条码在损溢区");
			try {
				ResponseUtil.write(response, jsonObject);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}else{
			//根据mcode查询收货单详细
			CodeMark codeMark = ReceiveDetailService.queryReceiveDetailIdByMcode(mcode);
			if (codeMark != null) {
				List<ReceiveDetail> receiveDetailList = ReceiveDetailService.selectAccurateByCodeApp(codeMark.getReceive_detail_id());
				if (receiveDetailList.size() > 0) {
					if (1 == receiveDetailList.get(0).getStatus()) {
						ZcMaterielAndTrayEntity zcMaterielAndTrayEntity = zcBindAndUnbindService.selectMaterielLocationByCodeDownLocation(mcode,"DJ");
						if(zcMaterielAndTrayEntity.getMateriel_code() != null && !"".equals(zcMaterielAndTrayEntity.getMateriel_code())){
							receiveDetailList.get(0).getReceiveCode().add(codeMark);
							//传递数据到页面
							jsonObject.put("status", "0");
							jsonObject.put("message", "质检区无此条码");
							//jsonObject.put("data", receiveDetailList.get(0));
						} else {
							receiveDetailList.get(0).getReceiveCode().add(codeMark);
							//传递数据到页面
							jsonObject.put("status", "1");
							//jsonObject.put("message", "此物料已下架");
							jsonObject.put("data", receiveDetailList.get(0));
						}
					}else if(0 == receiveDetailList.get(0).getStatus()){
						//传递数据到页面
						jsonObject.put("status", "0");
						jsonObject.put("message", "此物料未质检");
						//jsonObject.put("data", null);
					}else{
						//传递数据到页面
						jsonObject.put("status", "0");
						jsonObject.put("message", "此物料已上架");
						//jsonObject.put("data", null);
					}
				} else {
					//传递数据到页面
					jsonObject.put("status", "0");
					jsonObject.put("message", "查询不到此条码");
					jsonObject.put("data", null);
				}
				try {
					ResponseUtil.write(response, jsonObject);
				} catch (Exception e) {
					e.printStackTrace();
				}
			} else {
				
				/*codemark表中无此条码
				1.先在条码记录表中查询有没有，有，则表示此条码已出库。
				2.没有，就在receivemark表中查询，有，则表示，条码未收货，没有，表示系统无此条码*/
				
				//根据条码在条码记录表中查询此条码的信息
				BarCodeOperation param = new BarCodeOperation();
				param.setBarCode(mcode);
				List<BarCodeOperation> list = barCodeOperationService.queryAllByMution(param);
				
				if(list.size() > 0) {
					param.setWarehouse_id(Long.valueOf(warehouse_id));
					//根据条码和仓库id在操作记录表中查询此条码,存在，条码已出库，不存在，条码在别的仓库
					List<BarCodeOperation> list2 = barCodeOperationService.queryAllByMution(param);
					
					if(list2.size() > 0) {
						//此条码已出库
						//传递数据到页面
						jsonObject.put("status", "0");
						jsonObject.put("message", "条码已出库");
						jsonObject.put("data", null);
					}else {
						//此条码已出库
						//传递数据到页面
						jsonObject.put("status", "0");
						jsonObject.put("message", "该条码不属于本仓库");
						jsonObject.put("data", null);
					}
				}else {
					//根据条码，在receivemark表中查询
					ReceiveMark receiveMark = ReceiveDetailService.selectReceiveMarkByCode(mcode);
					
					if(receiveMark != null) {
						//传递数据到页面
						jsonObject.put("status", "0");
						jsonObject.put("message", "条码未收货，收货单号："+receiveMark.getReceiveDetail().getReceiveNumber());
						jsonObject.put("data", null);
					}else {
						//传递数据到页面
						jsonObject.put("status", "0");
						jsonObject.put("message", "系统无此条码");
						jsonObject.put("data", null);
					}
				}
				try {
					ResponseUtil.write(response, jsonObject);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	}
	/**
	 * 查询状态为1的收货单详细(盘点使用)
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("/selectAccurateByCodeAppInventory")
	public void selectAccurateByCodeAppInventory(HttpServletResponse response, String mcode) {
		JSONObject jsonObject = new JSONObject();
		//根据mcode查询收货单详细
		CodeMark codeMark = ReceiveDetailService.queryReceiveDetailIdByMcode(mcode);
		if (codeMark != null) {
			List<ReceiveDetail> receiveDetailList = ReceiveDetailService.selectAccurateByCodeApp(codeMark.getReceive_detail_id());
			if (receiveDetailList.size() > 0) {
				receiveDetailList.get(0).getReceiveCode().add(codeMark);
				jsonObject.put("status", "1");
				jsonObject.put("data", receiveDetailList.get(0));
			} else {
				//传递数据到页面
				jsonObject.put("status", "0");
				jsonObject.put("message", "查询不到此条码");
				jsonObject.put("data", null);
			}
			try {
				ResponseUtil.write(response, jsonObject);
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {
			//传递数据到页面
			jsonObject.put("status", "0");
			jsonObject.put("message", "查询不到此条码");
			jsonObject.put("data", null);
			try {
				ResponseUtil.write(response, jsonObject);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 查询状态为0的质检表APP
	 * @param response
	 * lz2019年11月7日 17:27:46新增接收app传递过来的warehouse_id参数
	 */
	@RequestMapping("/queryReceiveDetailQualityAPP")
	public void queryReceiveDetailQualityAPP(HttpServletResponse response, String warehouse_id) {
		log.info("APP查询状态为0的质检表传过来的仓库id为：" + warehouse_id);
		CodeMark codeMark;
		JSONObject jsonObject = new JSONObject();
		//根据mcode查询收货单详细
		List<ReceiveDetailQuality> receiveDetailQualityList = ReceiveDetailService.queryReceiveDetailQualityAPP(Long.parseLong(warehouse_id));
		for (int i = 0; i < receiveDetailQualityList.size(); i++) {
			List codeMarkList = new ArrayList<>();
			//List<CodeMark> codeMark1 = ReceiveDetailService.queryCodeMarkById(receiveDetailQualityList.get(i).getRemark());
			List<CodeMark> codeMark1 = ReceiveDetailService.queryCodeMarkById(receiveDetailQualityList.get(i).getId() + "");
			for (int j = 0; j < codeMark1.size(); j++) {
				codeMark = new CodeMark();
				codeMark.setReceive_detail_id(codeMark1.get(j).getReceive_detail_id());
				codeMark.setNum(codeMark1.get(j).getNum());
				codeMark.setCode(codeMark1.get(j).getCode());
				codeMark.setIs_ng(codeMark1.get(j).getIs_ng());
				codeMarkList.add(codeMark);
			}
			receiveDetailQualityList.get(i).setReceiveCode(codeMarkList);
		}
		if (receiveDetailQualityList.size() > AFFECT_ROW) {
			jsonObject.put("status", "1");
			jsonObject.put("message", "");
			jsonObject.put("data", receiveDetailQualityList);
		} else {
			jsonObject.put("status", "0");
			jsonObject.put("message", "查询数据为空");
			jsonObject.put("data", null);
		}
		try {
			ResponseUtil.write(response, jsonObject);
		} catch (Exception e) {
			log.info("APP查询状态为0的质检表返回给app的参数条数：" + jsonObject.size());
			e.printStackTrace();
		}
	}

	/**
	 * 查询状态为1的质检表
	 * @param response
	 * lz2019年11月7日 17:27:46新增接收app传递过来的warehouse_id参数
	 */
	@RequestMapping("/queryReceiveDetailQualityAPP1")
	public void queryReceiveDetailQualityAPP1(HttpServletResponse response, String warehouse_id) {
		log.info("APP查询状态为1的质检表传过来的仓库id为：" + warehouse_id);
		JSONObject jsonObject = new JSONObject();
		//根据mcode查询收货单详细
		List<ReceiveDetailQuality> receiveDetailQualityList = ReceiveDetailService.queryReceiveDetailQualityAPP1(Long.parseLong(warehouse_id));
		if (receiveDetailQualityList.size() > 0) {
			jsonObject.put("status", "1");
			jsonObject.put("message", "");
			jsonObject.put("data", receiveDetailQualityList);
		} else {
			jsonObject.put("status", "0");
			jsonObject.put("message", "查询数据为空");
			jsonObject.put("data", null);
		}
		try {
			ResponseUtil.write(response, jsonObject);
		} catch (Exception e) {
			log.info("APP查询状态为1的质检表返回给app的参数条数：" + jsonObject.size());
			e.printStackTrace();
		}
	}

	/**
	 * 修改状态为0的质检表
	 * @param response
	 * @throws Exception
	 * lz2019年11月7日 17:38:34添加接收参数warehouse_id
	 */
	@RequestMapping("/updateReceiveDetailQualityAPP")
	public void updateReceiveDetailQualityAPP(String json, String person, HttpServletResponse response, String warehouse_id) {
		Long affactRow = 0L;
		Workload workload;
		//CodeMark codeMark;
		Gson gson = new Gson();
		List<ReceiveDetailQuality> receiveDetailQualityList = gson.fromJson(json, new TypeToken<List<ReceiveDetailQuality>>() {}.getType());
		//JSONObject jsonObject2 = JSONObject.fromObject(json);
		//ReceiveDetailQuality receiveDetailQuality = (ReceiveDetailQuality)JSONObject.toBean(jsonObject2, ReceiveDetailQuality.class);
		JSONObject jsonObject = new JSONObject();
		//根据receiveDetailQuality修改良品数和不良品数
		for (ReceiveDetailQuality receiveDetailQuality : receiveDetailQualityList) {
		//for (int i = 0; i < receiveDetailQualityList.size(); i++) {
			affactRow = ReceiveDetailService.updateReceiveDetailQualityAPP(receiveDetailQuality);
			//如果修改成功则给工作量实体添加数据
			for (int j = 0; j < receiveDetailQuality.getWorkloadList().size(); j++) {
				workload = new Workload();
				workload.setReceiveDetailQuality_id(receiveDetailQuality.getId());
				workload.setWorkman(receiveDetailQuality.getWorkloadList().get(j).getWorkman());
				workload.setGood_num(receiveDetailQuality.getWorkloadList().get(j).getGood_num());
				workload.setNgood_num(receiveDetailQuality.getWorkloadList().get(j).getNgood_num());
				//添加每种物料对应的工作量
				ReceiveDetailService.addWorkload(workload);
			}
			//现在条码
			List<CodeMark> codeMarkListX = receiveDetailQuality.getReceiveCode();
			//原有条码
			List<CodeMark> codeMarkListY = ReceiveDetailService.queryCodeMarkById(receiveDetailQuality.getId() + "");
			//现在条码比较原有条码新增
			List<CodeMark> codeMarkListXS = new ArrayList<>();
			//现在条码比较原有条码没有的
			List<CodeMark> codeMarkListYS = new ArrayList<>();
			
			for (int j = 0; j < codeMarkListY.size(); j++) {
				//在新条码中是否查询到此次循环旧条码 0 否 1是
				int flg = 0;
				for (int k = 0; k < codeMarkListX.size(); k++) {
					//此次循环新条码  == 此次循环旧条码
					if(codeMarkListX.get(k).getCode().equals(codeMarkListY.get(j).getCode())){
						//修改物料托盘信息
						ZcMaterielAndTrayEntity zcMaterielAndTrayEntity = ReceiveDetailService.queryMaterielTrayByCode(codeMarkListY.get(j).getCode());
						if(zcMaterielAndTrayEntity != null){
							int num = zcMaterielAndTrayEntity.getmNum()-codeMarkListY.get(j).getNum()+codeMarkListX.get(k).getNum();
							inventoryService.updateById(zcMaterielAndTrayEntity.getId()+"", "mNum", num+"", "zc_materiel_tray");
						}
						//修改记录
						//根据精准码查询是否存在
						CodeMark CodeMark = ReceiveDetailService.queryCodeMarkByCode(codeMarkListY.get(j));
						if (CodeMark != null) {
							ReceiveDetailService.updateCodeMark(codeMarkListX.get(k));
						} else {
							//绑定新条码
							ReceiveDetailService.addCodeMark(codeMarkListX.get(k));
						}
						flg = 1;
						break;
					}
				}
				//没有找到
				if(flg == 0){
					//删除托盘物料
					ZcMaterielAndTrayEntity zcMaterielAndTrayEntity = ReceiveDetailService.queryMaterielTrayByCode(codeMarkListY.get(j).getCode());
					if(zcMaterielAndTrayEntity != null){
						String mCode = zcMaterielAndTrayEntity.getMateriel_code();
						//用空字符串替换旧条码
						String newCode2 = mCode.replace(codeMarkListY.get(j).getCode()+",", "");
						if(newCode2.length() == 0){
							//如果托盘空了，则删除这条数据(现在不能删，只有添加新条码后，再盘点托盘为空，进行删除，新条码有可能放回来)
							ReceiveDetailService.deleteMaterielTrayById(zcMaterielAndTrayEntity.getId());
						}else{
							//把替换后的条码集合放回原来托盘
							ReceiveDetailService.updateMaterielTrayByCode(zcMaterielAndTrayEntity.getId() + "", newCode2);
							//根据精准码查询是否存在
							CodeMark codeMark = ReceiveDetailService.queryCodeMarkByCode(codeMarkListY.get(j));
							if (codeMark != null) {
								inventoryService.updateById(zcMaterielAndTrayEntity.getId()+"", "mNum", (zcMaterielAndTrayEntity.getmNum()-codeMark.getNum())+"", "zc_materiel_tray");
							} 
						}
					}
					//删除记录
					stockOutService.deleteCodemarkOutByCode(codeMarkListY.get(j).getCode());
				}
			}
			
			for (int j = 0; j < codeMarkListX.size(); j++) {
				//在新条码中是否查询到此次循环旧条码 0 否 1是
				int flg = 0;
				for (int k = 0; k < codeMarkListY.size(); k++) {
					if(codeMarkListX.get(j).getCode().equals(codeMarkListY.get(k).getCode())){
						flg = 1;
						break;
					}
				}
				if(flg == 0){
					codeMarkListXS.add(codeMarkListX.get(j));
				}
			}
			if(codeMarkListXS.size() > 0){
				String codes = "";
				int sum = 0;
				for (CodeMark codeMark : codeMarkListXS) {
					codes += codeMark.getCode() + ",";
					sum += codeMark.getNum();
					//绑定新条码
					ReceiveDetailService.addCodeMark(codeMark);
				}
				ZcMaterielAndTrayEntity zcMaterielAndTrayEntity = new ZcMaterielAndTrayEntity();
				zcMaterielAndTrayEntity.setMid(receiveDetailQuality.getMid());
				zcMaterielAndTrayEntity.setmBatch(receiveDetailQuality.getPici());
				zcMaterielAndTrayEntity.setMateriel_code(codes);
				String tray_code = System.currentTimeMillis() + "";
				zcMaterielAndTrayEntity.setTray_code(tray_code);
				zcMaterielAndTrayEntity.setmNum(sum);
				zcMaterielAndTrayEntity.setBinding_person(Long.valueOf(person));
				zcMaterielAndTrayEntity.setBinding_date(DateUtil.dateFormat3());
				inventoryService.MaterielTrayInsert(zcMaterielAndTrayEntity);
				ZcTrayAndLocationEntity a = new ZcTrayAndLocationEntity();
				a.setLocation_code("DJ");
				//lz新增warehouse_id
				a.setWarehouse_id(Long.parseLong(warehouse_id));
				ZcTrayAndLocationEntity zcTrayAndLocationEntityOld = zcBindAndUnbindService.selectTrayCodeByLocationCode(a);
				//3、如果不为空，修改数据
				if(zcTrayAndLocationEntityOld != null){
					String trayCodes = zcTrayAndLocationEntityOld.getTray_code() + zcMaterielAndTrayEntity.getTray_code() + ",";
					inventoryService.updateById(zcTrayAndLocationEntityOld.getId() + "", "tray_code", trayCodes, "zc_tray_location");
				} else {
					//4、新增库位至待检区
					ZcTrayAndLocationEntity zcTrayAndLocationEntity = new ZcTrayAndLocationEntity();
					//托盘码
					zcTrayAndLocationEntity.setTray_code(tray_code);
					//库区编码
					zcTrayAndLocationEntity.setLocation_code("DJ");
					//绑定人
					zcTrayAndLocationEntity.setBinding_person(zcMaterielAndTrayEntity.getBinding_person());
		    		//绑定时间
					zcTrayAndLocationEntity.setBinding_date(zcMaterielAndTrayEntity.getBinding_date());
					//lz新增warehouse_id
					zcTrayAndLocationEntity.setWarehouse_id(Long.parseLong(warehouse_id));
					inventoryService.trayLocationInsert(zcTrayAndLocationEntity);
				}
			}
			
			/*//判断CodeMark是修改还是新增
			for (int k = 0; k < receiveCode.size(); k++) {
				//根据精准码查询是否存在
				CodeMark CodeMark = ReceiveDetailService.queryCodeMarkByCode(receiveCode.get(k));
				if (CodeMark != null) {
					ReceiveDetailService.updateCodeMark(receiveCode.get(k));
				} else {
					//绑定新条码
					ReceiveDetailService.addCodeMark(receiveCode.get(k));
				}
			}*/
			
			//给不良品库存添加数据,首先根据物料id和批次查询是否存在
			//TODO
			//int nowNum = receiveDetailQualityList.get(i).getNg_num();
			/**
			 * 根据批次和物料id查询不良品库是否存在该物料
			 */
			/*ZcRejectsWarehouseEntity zcRejectsWarehouseEntity = ReceiveDetailService.
					queryZcRejectsWarehouseEntityByMbatchAngMid(receiveDetailQualityList.get(i));
			//如果存在
			if (zcRejectsWarehouseEntity != null) {
				int totality = zcRejectsWarehouseEntity.getTotality();
				totality = nowNum + totality;
				receiveDetailQualityList.get(i).setNg_num(totality);
				ReceiveDetailService.updateZcRejectsWarehouseEntity(receiveDetailQualityList.get(i));
			} else {
				receiveDetailQualityList.get(i).setPerson(person);
				ReceiveDetailService.addZcRejectsWarehouseEntity(receiveDetailQualityList.get(i));
			}
			//将库存表中的不良品数量减掉
			ReceiveDetailService.updateInventoryInfoNum(receiveDetailQualityList.get(i));*/
		}
		if (affactRow > AFFECT_ROW) {
			jsonObject.put("status", "1");
			jsonObject.put("message", "");
			jsonObject.put("data", "质检完成");
		} else {
			jsonObject.put("status", "0");
			jsonObject.put("message", "质检失败");
			jsonObject.put("data", "0");
		}
		
		//----------------------给历史记录表插入数据-------------------------------------
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String time = format.format(new Date());
		for(ReceiveDetailQuality detail : receiveDetailQualityList){
			BarCodeOperation bar = new BarCodeOperation();
			bar.setBatch(detail.getPici());
			bar.setOperator(Long.parseLong(person));
			bar.setOperatingTime(time);
			bar.setMaterielId(detail.getMid());
			bar.setType("质检");
			//lz新增warehouse_id
			bar.setWarehouse_id(Long.parseLong(warehouse_id));
			if(affactRow > AFFECT_ROW){
				bar.setResult("成功");
			}else{
				bar.setResult("失败");
			}
			for(CodeMark cm : detail.getReceiveCode()){
				bar.setBarCode(cm.getCode());
				bar.setCodeNum(cm.getNum());
				barCodeOperationService.insert(bar);
			}
		}
		//----------------------给历史记录表插入数据-------------------------------------
		try {
			ResponseUtil.write(response, jsonObject);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 精准拆箱作业
	 * @param json1 拆箱前条码
	 * @param json2	拆箱后条码
	 * @param userId	用户ID（拆箱作业员工）
	 * llm 19.11.11 新增 （重写下面的拆箱方法）
	 */
	@RequestMapping("/devanning2")
	@ResponseBody
	public Map<String, Object> devanning(String json1, String json2, String userId){
		Gson gson = new Gson();
		//拆箱前
		List<CodeMark> unpackingBeforeCodes = gson.fromJson(json1, new TypeToken<List<CodeMark>>() {}.getType());
		//拆箱后
		List<CodeMark> unpackingAfterCodes = gson.fromJson(json2, new TypeToken<List<CodeMark>>() {}.getType());
		//工作量
		List<Workload> workloads = gson.fromJson(userId, new TypeToken<List<Workload>>() {}.getType());
		Map<String, Object> map = devaningWorkService.devanning(unpackingBeforeCodes, unpackingAfterCodes, workloads);
		return map;
	}
	
	/**
	 * 拆箱
	 * @param json1
	 * @param json2
	 * @param userId
	 * @param response          
	 * LZ新增warehouse_id参数   
	 */
	@RequestMapping("/devanning")
	public void devanning(String json1, String json2, String userId, HttpServletResponse response, String warehouse_id) {
		JSONObject jsonObject = new JSONObject();
		Gson gson = new Gson();
		//拆箱前
		List<CodeMark> codeMarkList1 = gson.fromJson(json1, new TypeToken<List<CodeMark>>() {}.getType());
		//拆箱后
		List<CodeMark> codeMarkList2 = gson.fromJson(json2, new TypeToken<List<CodeMark>>() {}.getType());
		//工作量
		List<Workload> workList = gson.fromJson(userId, new TypeToken<List<Workload>>() {}.getType());
		//删除缓存区
		
		//遍历查询是否有和剩余条码相同的条码
		int flag = 1;
		String codeArr3 = "";
		List<CodeMark> codeMarkList3 = materielService.queryAllCode(codeMarkList1.get(0).getCode());
		List<String> list = new ArrayList<>();
		for(CodeMark cm : codeMarkList1){
			list.add(cm.getCode());
		}
		
		List<String> list5 = new ArrayList<>();
		for(CodeMark cm : codeMarkList2){
			list5.add(cm.getCode());
		}
		
		list5.removeAll(list);
		
		for (String  c4 : list5) {
			for (CodeMark c3 : codeMarkList3) {
				if (c4.equals(c3.getCode())) {
					flag=0;
					codeArr3 += c4 + ",";
				}
			}
		}
		if(flag == 1) {
		
			//连雷明 修改
			//替换条码
			//1.1、找到旧条码中第一个条码的位置
			CodeMark codeMark = cancellingStockDetailService.queryCodeByCode(codeMarkList1.get(0).getCode());
			String code = codeMarkList1.get(0).getCode()+",";
			ZcMaterielAndTrayEntity zcMaterielAndTrayEntity = ReceiveDetailService.queryMaterielTrayByCode(code);
			if(zcMaterielAndTrayEntity != null){
				int afacct = unpackDetalService.devanningWork(codeMarkList1, codeMarkList2, workList, warehouse_id, codeMark, zcMaterielAndTrayEntity);
				if ( afacct > AFFECT_ROW) {
					//传递数据到页面
					jsonObject.put("status", "1");
					jsonObject.put("message", "");
					jsonObject.put("data", "提交成功");
				}else {
					//传递数据到页面
					jsonObject.put("status", "0");
					jsonObject.put("message", "提交失败");
					jsonObject.put("data", "0");
				}
			}else{
				//传递数据到页面
				jsonObject.put("status", "0");
				jsonObject.put("message", "请扫正确条码");
				jsonObject.put("data", "0");
			}
		}else {
			jsonObject.put("status", "0");
			jsonObject.put("message", "输入的条码"+codeArr3+"与原条码重复");
			jsonObject.put("data", "0");
		}
		try {
			ResponseUtil.write(response, jsonObject);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 根据精准码查询是否存在
	 * @param mcode
	 * @param response
	 */
	@RequestMapping("/queryRepeatAccurateByCodeApp")
	public void queryRepeatAccurateByCodeApp(String mcode, HttpServletResponse response) {
		JSONObject jsonObject = new JSONObject();
		CodeMark codemark = ReceiveDetailService.queryRepeatAccurateByCodeApp(mcode);
		if (codemark != null) {
			jsonObject.put("status", "0");
			jsonObject.put("message", "条码已使用");
			jsonObject.put("data", codemark.getCode());
		} else {
			jsonObject.put("status", "1");
			jsonObject.put("message", "");
			jsonObject.put("data", mcode);
		}
		try {
			ResponseUtil.write(response, jsonObject);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 查询有仓库操作员权限的人员
	 * @param response
	 */
	@RequestMapping("/queryRoleUser")
	public void queryRoleUser(HttpServletResponse response) {
		JSONObject jsonObject = new JSONObject();
		List<String> userNmaeList = ReceiveDetailService.queryRoleUser();
		if (userNmaeList.size() > 0) {
			jsonObject.put("status", "1");
			jsonObject.put("message", "");
			jsonObject.put("data", userNmaeList);
		} else {
			jsonObject.put("status", "0");
			jsonObject.put("message", "查询数据为空");
			//jsonObject.put("data", "");
		}
		try {
			ResponseUtil.write(response, jsonObject);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 将入库后的不良品入库
	 * @param json
	 * @param person
	 * @param response
	 */
	@RequestMapping("/ngInstock")
	public void ngInstock(String json, String person, HttpServletResponse response, String warehouse_id) {
		BarCodeConversionRecord record = new BarCodeConversionRecord();
		Gson gson = new Gson();
		JSONObject jsonObject = new JSONObject();
		List<CodeMark> codeMarkList = gson.fromJson(json, new TypeToken<List<CodeMark>>() {}.getType());
		for (CodeMark codeMark : codeMarkList) {
			//如果是良品
			if (codeMark.getIs_ng() == 0) {
				Long affact = ReceiveDetailService.updateIsngStatus(codeMark.getCode());
				//根据条码查询物料和批次
				ReceiveDetailQuality receiveDetailQuality = ReceiveDetailService.queryReceiveDetailQualityByCode(codeMark.getCode());
				record.setMateriel_id(receiveDetailQuality.getMid());
				record.setMateriel_count(codeMark.getNum());
				record.setOperate_id(Long.parseLong(person));
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				record.setOperate_time(sdf.format(new Date()));
				record.setPrefix_code(codeMark.getCode());
				record.setOperate_type("良品转不良品");
				record.setTrans_reason("");
				record.setImg_url("");
				//LZ新增warehouse_id字段
				record.setWarehouse_id(Long.parseLong(warehouse_id));
				//新增条码转换记录
				ReceiveDetailService.insertBarCodeConversionRecord(record);
				if (affact > AFFECT_ROW) {
					jsonObject.put("status", "1");
					jsonObject.put("data", "转换成功");
				} else {
					jsonObject.put("status", "0");
					jsonObject.put("message", "转换失败");
				}
			} else {
				//不良品转良品
				Long affact = ReceiveDetailService.updateIsngStatus1(codeMark.getCode());
				//根据条码查询物料和批次
				ReceiveDetailQuality receiveDetailQuality = ReceiveDetailService.queryReceiveDetailQualityByCode(codeMark.getCode());
				record.setMateriel_id(receiveDetailQuality.getMid());
				record.setMateriel_count(codeMark.getNum());
				record.setOperate_id(Long.parseLong(person));
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				record.setOperate_time(sdf.format(new Date()));
				record.setPrefix_code(codeMark.getCode());
				record.setOperate_type("不良品转良品");
				record.setTrans_reason("");
				record.setImg_url("");
				//LZ新增warehouse_id字段
				record.setWarehouse_id(Long.parseLong(warehouse_id));
				//新增条码转换记录
				ReceiveDetailService.insertBarCodeConversionRecord1(record);
				if (affact > AFFECT_ROW) {
					jsonObject.put("status", "1");
					jsonObject.put("data", "转换成功");
				} else {
					jsonObject.put("status", "0");
					jsonObject.put("message", "转换失败");
				}
			}
			try {
				ResponseUtil.write(response, jsonObject);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		
	}
	
	/**
	 * 良品不良品转换
	 * @param json
	 * @param person
	 * @param response
	 */
	@RequestMapping("/transCodeMarkStatus")
	public void transCodeMarkStatus(String json, String person, HttpServletResponse response) {
		Gson gson = new Gson();
		List<CodeMark> codeMarkList = gson.fromJson(json, new TypeToken<List<CodeMark>>() {}.getType());
		for (CodeMark codeMark : codeMarkList) {
			//根据条码修改条码状态
			Long affact = ReceiveDetailService.updateIsngStatus(codeMark.getCode());
			/*if (affact > 0) {
				//根据条码查询物料和批次
				ReceiveDetailQuality receiveDetailQuality = ReceiveDetailService.queryReceiveDetailQualityByCode(codeMark.getCode());
				//1.首先去查询不良品库中该物料是否存在
				ZcRejectsWarehouseEntity zcRejectsWarehouseEntity = ReceiveDetailService.
						queryZcRejectsWarehouseEntityByMbatchAngMid(receiveDetailQuality);
				//如果存在
				if (zcRejectsWarehouseEntity != null) {
					int totality = zcRejectsWarehouseEntity.getTotality();
					totality = receiveDetailQuality.getNg_num() + totality;
					receiveDetailQuality.setNg_num(totality);
					ReceiveDetailService.updateZcRejectsWarehouseEntity(receiveDetailQuality);
				} else {
					receiveDetailQuality.setPerson(person);
					ReceiveDetailService.addZcRejectsWarehouseEntity(receiveDetailQuality);
				}
			}*/
		}
		JSONObject jsonObject = new JSONObject();
		List<String> userNmaeList = ReceiveDetailService.queryRoleUser();
		if (userNmaeList.size() > AFFECT_ROW) {
			jsonObject.put("status", "1");
			jsonObject.put("message", "");
			jsonObject.put("data", "不良品入库成功");
		} else {
			jsonObject.put("status", "0");
			jsonObject.put("message", "不良品入库失败");
			jsonObject.put("data", "");
		}
		try {
			ResponseUtil.write(response, jsonObject);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 查询状态为0的计数入库单
	 * @param response
	 */
	@RequestMapping("selectAllReceipt")
	public void selectAllReceipt(HttpServletResponse response){
		ZcGeneralQueryEntity zcGeneralQueryEntity = new ZcGeneralQueryEntity();
		//未收货
		List<Receive> list = zcSimplificationInService.selectSimplificationInListAll(zcGeneralQueryEntity);
		
		JSONObject jsonObject = new JSONObject();
		int count = list.size();
		if (count > AFFECT_ROW) {
			//传递数据到页面
		    jsonObject.put("status", "1");
		    jsonObject.put("message", "");
		    jsonObject.put("data", list);
		}else {
			//传递数据到页面
		    jsonObject.put("status", "0");
		    jsonObject.put("message", "查询数据为空");
		    jsonObject.put("data", list);
		}
		try {
			ResponseUtil.write(response, jsonObject);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/**
	 * 通过收货单号查详情（计数）
	 */
	@RequestMapping("selectReceiptDtailByNumber")
	public void selectReceiptDtailByNumber(String receiveNumber,HttpServletResponse response){
		ReceiveDetail param = new ReceiveDetail();
		param.setReceiveNumber(receiveNumber);
		List<ReceiveDetail> list = ReceiveDetailService.queryAllByMution(param );
		
		JSONObject jsonObject = new JSONObject();
		int count = list.size();
		if (count > 0) {
			//传递数据到页面
		    jsonObject.put("status", "1");
		    jsonObject.put("message", "");
		    jsonObject.put("data", list);
		}else {
			//传递数据到页面
		    jsonObject.put("status", "0");
		    jsonObject.put("message", "查询数据为空");
		    jsonObject.put("data", list);
		}
		try {
			ResponseUtil.write(response, jsonObject);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/**
	 * 收货提交(计数)
	 * @param Details 收货详情集合
	 * @param person 收货人
	 * @param sure_name 回收容器数量
	 * @param response 响应
	 * @throws Exception 异常
	 */
	@RequestMapping("/submitReceipt")
	public void submitReceipt(String Details, String person, String sure_name, HttpServletResponse response, String warehouse_id){
		//初始化影响行数
		int affact1 = 0;
		Long affact = 0L;
		//json参数转化为实体集合
		Gson gson = new Gson();
		List<ReceiveDetail> receiveDetailList = gson.fromJson(Details, new TypeToken<List<ReceiveDetail>>() {}.getType());
		//遍历修改
		for (ReceiveDetail receiveDetail : receiveDetailList) {
			/*==================新表添加数据================*/
			//ReceiveDetailService.addReceiveDetailInstock(receiveDetail);
			/*==================修改收货详细表信息==========*/
			affact1 = ReceiveDetailService.update(receiveDetail);
			/*==================修改质检表信息==========*/
			//ReceiveDetailService.updateReceiveDetailQuality(receiveDetail);
			/*====================添加库存=======================*/
			//int number = receiveDetail.getCodeNum();
			//ZcInventoryInfoEntity zcInventoryInfoEntity = upService.selectByMid2(receiveDetail.getMid() + "", receiveDetail.getPici());
			/************************llm 19.11.08 修改 start ***************************/
			ZcInventoryInfoEntity zcInventoryInfoEntity = upService.selectByMid2(receiveDetail.getMid() + "", receiveDetail.getPici(), warehouse_id);
			/************************llm 19.11.08 修改 end   ***************************/
			//1.如果查到
			if (zcInventoryInfoEntity != null) {
				int mNum = zcInventoryInfoEntity.getmNum();
				//1.如果是精准码,只存入总数
				//mNum = number + mNum;
				//总数量（个数）
				zcInventoryInfoEntity.setmNum(mNum);
				affact = upService.editStockOnlyCount(zcInventoryInfoEntity);
			} else {
				ZcInventoryInfoEntity zcInventoryInfoEntity1 = new ZcInventoryInfoEntity();
				zcInventoryInfoEntity1.setMid(receiveDetail.getMid());
				//zcInventoryInfoEntity1.setmNum(receiveDetail.getCodeNum());
				zcInventoryInfoEntity1.setmBatch(receiveDetail.getPici());
				zcInventoryInfoEntity1.setEnterPerson(Long.parseLong(person));
				affact = upService.insertStockOnlyCount(zcInventoryInfoEntity1);
			}
		}

		//获取收货单号
		ReceiveDetail receiveDetail = receiveDetailList.get(0);
		//更改一级状态  --为已收货
		Receive receive = new Receive();
		receive.setReceiveNumber(receiveDetail.getReceiveNumber());
		receive.setIsSimple("1");
		List<Receive> receives = ReceiveService.allByMution(receive);
		
		if(receives.size()  > 0) {
			Receive receive2 = receives.get(0);
			receive2.setState(1);
			receive2.setReceiveDate(DateUtil.dateFormat3());
			receive2.setReceiveName(person);
			receive2.setSendCompany(null);
			//回收容器数量
			receive2.setSureName(sure_name);
			ReceiveService.update(receive2);
		}
		JSONObject jsonObject = new JSONObject();
		if (affact > 0) {
			//传递数据到页面
		    jsonObject.put("status", "1");
		    jsonObject.put("message", "");
		    jsonObject.put("data", "提交成功");
		}else {
			//传递数据到页面
		    jsonObject.put("status", "0");
		    jsonObject.put("message", "提交失败");
		    jsonObject.put("data", "0");
		}
		try {
			ResponseUtil.write(response, jsonObject);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 根据收货单单号查询所有ReceiveMark实体
	 * @param receiveId 收货单id
	 * @param mcode
	 * @param response
	 */
	@RequestMapping("/queryReceiveCodeByReceiveId")
	public void queryReceiveCodeByReceiveId(String receiveId, String mcode, HttpServletResponse response){
		CodeMark codeMark1 = new CodeMark();
		codeMark1.setCode(mcode);
		//1.先查询CodeMark，如果查到直接返回此条码已收货
		//2.先查询CodeMark，如果未查到，再去查ReceiveMark，还没查到，返回app"此条码不存在"
		//3.先查询CodeMark，如果未查到，再去查ReceiveMark，查到，返回ReceiveMark实体
		JSONObject jsonObject = new JSONObject();
		//根据条码查询CodeMark实体
		CodeMark codeMark = ReceiveDetailService.queryCodeMarkByCode(codeMark1);
		if (codeMark != null) {
			//传递数据到页面
		    jsonObject.put("status", "0");
		    jsonObject.put("message", "此物料已收货");
		} else {
			/*//根据收货单单号和条码查询ReceiveMark实体
			ReceiveMark receiveMark = ReceiveDetailService.queryReceiveCodeByReceiveId(receiveId, mcode);
			
			if (receiveMark != null) {
				//传递数据到页面
			    jsonObject.put("status", "1");
			    jsonObject.put("data", receiveMark);
			} else {
				//传递数据到页面
			    jsonObject.put("status", "0");
			    jsonObject.put("message", "此条码不存在");
			}*/
			//根据条码查询ReceiveMark表中 有无此数据
			ReceiveMark receiveMark = ReceiveDetailService.selectReceiveMarkByCode(mcode);
			if(receiveMark != null) {
				//ReceiveMark表中 有 此数据
				if(receiveMark.getReceiveDetail().getReceiveNumber() != null && receiveId != null) {
					String receiveNumber = receiveMark.getReceiveDetail().getReceiveNumber();
					if(receiveId.equals(receiveNumber)){
						//传递数据到页面
					    jsonObject.put("status", "1");
					    jsonObject.put("data", receiveMark);
					}else {
						jsonObject.put("status", "0");
					    jsonObject.put("message", "此条码在"+receiveNumber+"收货单中");
					}
				}
				
			}else {
				//ReceiveMark表中 无 此数据
				//传递数据到页面
			    jsonObject.put("status", "0");
			    jsonObject.put("message", "系统无此条码");
			}
		}
		try {
			ResponseUtil.write(response, jsonObject);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 分页查询条码转换记录
	 * @param response
	 * @param criteria
	 * @修改记录 LZ新增session获取当前登录人
	 */
	@RequestMapping("/queryBarCodeConversionRecordCriteria")
	public void queryBarCodeConversionRecordCriteria(HttpServletResponse response, LzQueryCriteria criteria, HttpSession session){
		//LZ新增仓库id字段
		Long warehouse_id = (Long) session.getAttribute("warehouse_id");
		//LZ给keyword07参数赋值
		criteria.setKeyword07(warehouse_id + "");
		List<BarCodeConversionRecord> recordList = ReceiveDetailService.queryBarCodeConversionRecordCriteria(criteria);
		int count = ReceiveDetailService.countBarCodeConversionRecordCriteria(criteria);
		JSONObject jsonObject = new JSONObject();
		JSONArray jsonArray = JSONArray.fromObject(recordList);
		jsonObject.put("code", 0);
		jsonObject.put("data", jsonArray);
		jsonObject.put("count", count);
		try {
			ResponseUtil.write(response, jsonObject);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 良品转不良品确认
	 * @param response
	 */
	@RequestMapping("/updateConfirm")
	public void updateConfirm(HttpServletResponse response, String id){
		Long affectRow = ReceiveDetailService.updateConfirm(Long.parseLong(id));
		if (affectRow > AFFECT_ROW) {
			try {
				ResponseUtil.write(response, affectRow);
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {
			try {
				ResponseUtil.write(response, AFFECT_ROW);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	
	/**
	 * 查询条码是否存在
	 * @param response
	 * @param code 条码
	 */
	@RequestMapping("/queryLifeByCode")
	public void queryLifeByCode(HttpServletResponse response, String code){
		JSONObject jsonObject = new JSONObject();
		CodeMark codeMark = new CodeMark();
		codeMark.setCode(code);
		//根据条码查询CodeMark实体
		CodeMark cm = ReceiveDetailService.queryCodeMarkByCode(codeMark);
		if (cm == null) {
			//传递数据到页面
		    jsonObject.put("status", "1");
		    jsonObject.put("data", code);
		} else {
			//传递数据到页面
		    jsonObject.put("status", "0");
		    jsonObject.put("message", "此条码已存在");
		}
		try {
			ResponseUtil.write(response, jsonObject);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
